<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use \app\common\model\User;
use \app\common\model\Homeworkassignment as HomeworkassignmentModel;
use \app\common\model\HomeworkAssignmentRelation;
use \app\common\model\Homework;
use \app\common\model\TeacherClassesRelation;
use \app\common\model\StudentClassesRelation;
use \app\common\model\HomeworkCorrections;
use \app\common\model\Teacherreviews;
use \app\common\model\HomeworkAssignmentImageRelation;






/**
 * 布置作业接口
 */
class Homeworkassignment extends Api
{
    /**
     * 布置作业列表
     * @var array
     */
    protected $noNeedRight = '*';

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HomeworkassignmentModel;
        $this->user = new User;
        $this->homeworkAssignmentRelation = new HomeworkAssignmentRelation;
        $this->homework = new Homework;
        $this->teacherClassesRelation = new TeacherClassesRelation;
        $this->studentClassesRelation = new StudentClassesRelation;
        $this->homeworkAssignmentImageRelation = new HomeworkAssignmentImageRelation;
        $this->homeworkCorrections = new HomeworkCorrections;
        $this->teacherreviews = new Teacherreviews;

    }

   /**
     * 查询布置作业表
     * @ApiTitle    (查询布置作业表)
     * @ApiMethod  (GET)
     * @ApiParams   (name="teacher_id", type="int", required=false, description="教师ID")
     * @ApiParams   (name="page", type="integer", required=false, description="页码")
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
         'code':'200',
        'msg':'查询成功',
        'time': "",
        'data': {
            'list': $list,
            'total': $total,
            'current_page': $page,
            'per_page': $limit,
            'last_page': $lastPage
        }
        })
    */
    public function assignmentIndex()
    {
        $teacher_id = $this->request->get('teacher_id');
        // 获取分页参数，默认第1页，每页10条
        $page = $this->request->param('page/d', 1);
        $limit = $this->request->param('limit/d', 10);
        
        // 查询总数
        $total = $this->model->dataCount();

        
        // 查询分页数据
        // $list = $this->model->alias('a')
        //     ->join('user t', 'a.teacher_id = t.id', 'left')  
        //     ->where('a.teacher_id', $teacher_id)
        //     ->order('a.id', 'desc')
        //     ->field('a.*, t.username as teacher_name')
        //     ->page($page, $limit)
        //     ->select();

        $teacher_name = $this->user->dataInfo([
            'id' => $teacher_id
        ],'id,nickname');


        if(empty($teacher_name)){
            $this->success('未找到教师信息',[]); 
        }
        $list = $this->model->dataList([
            'teacher_id' => $teacher_id
        ]);
        foreach($list as $key => $value){
            $list[$key]['teacher_name'] = $teacher_name['nickname'];
        } 
        if (empty($list)) {
            $this->success('查询记录为空', []); 
        }
        foreach($list as $key => $value){
            $submit_records =  $this->homeworkAssignmentRelation->dataList([
                'assignment_id' => $value['id']
            ]);
            // $submit_records = Db::name('homework_assignment_relation')
            //     ->where('assignment_id', $value['id'])
            //     ->select();
            
            $homework_ids = array_column($submit_records, 'homework_id');
            
            $submit_count = 0;
            if (!empty($homework_ids)) {
                $submit_count = $this->homework->dataCount([
                    'id' => ['in', $homework_ids]
                ]);
                // $submit_count = Db::name('homework')
                //     ->where('id', 'in', $homework_ids)
                //     ->group('student_id')  // 按 student_id 去重
                //     ->count();
            }
            $teacher_count = $this->teacherClassesRelation->dataList(['teacher_id' => $value['teacher_id']]);
            // $teacher_count = Db::name('teacher_classes_relation')
            //     ->where('teacher_id', $value['teacher_id'])
            //     ->select();
            $teacher_count = array_column($teacher_count, 'classes_id');
            $teacher_count = $this->studentClassesRelation->dataCount([
                'classes_id' => ['in', $teacher_count]
            ]);

            // $teacher_count = Db::name('student_classes_relation')
            //     ->where('classes_id', 'in', $teacher_count)
            //     ->count();
            $list[$key]['submit_count'] = $submit_count;
            $list[$key]['total'] = $teacher_count;
            if ($teacher_count > 0) {
                $list[$key]['submit_rate'] = round(($submit_count / $teacher_count) * 100, 2) . '%';
            } else {
                $list[$key]['submit_rate'] = '0%';
            }
        }
        
        $this->success('查询成功', [
            'list' => $list,
            'total' => $total,
            'current_page' => $page,
            'per_page' => $limit,
        ]);
    }

     /**
     * 学生布置作业列表
     * @ApiTitle    (学生布置作业列表)
     * @ApiMethod  (GET)
     * @ApiParams   (name="page", type="integer", required=false, description="页码")
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量")
     * @ApiParams   (name="student_id", type="integer", required=true, description="学生ID")
     * @ApiParams   (name="status", type="integer", required=true, description="提交状态") //1未提交
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
            'code':'200',
            'msg':'查询成功',
            'time': "",
            'data': ""
        })
     */
    public function studentAssignmentIndex()
    {
        $student_id = $this->request->get('student_id');
        $status = $this->request->get('status');
    
        // 参数验证
        if (empty($student_id)) {
            $this->error('学生ID不能为空');
        }
        if (!is_numeric($student_id)) {
            $this->error('参数类型不正确');
        }
        // 获取学生班级信息
        $classes_id = $this->studentClassesRelation->dataInfo([
            'student_id' => $student_id
        ]);
        // $classes_id = Db::name('student_classes_relation')
        //     ->where('student_id', $student_id)
        //     ->find();
        if (!$classes_id) {
            $this->success('学生没有班级信息');
        }
    
        // 获取教师ID
        $teacher_id = $this->teacherClassesRelation->dataMemberId([
            'classes_id' => $classes_id['classes_id']
        ],'teacher_id');
        // $teacher_id = Db::name('teacher_classes_relation')
        //     ->where('classes_id', $classes_id['classes_id'])
        //     ->column('teacher_id');
    
        // 获取所有布置的作业
        $assignments = $this->model->dataList([
            'teacher_id' => ['in', $teacher_id]
        ]);
        // $assignments = Db::name('homework_assignment')
        //     ->where('teacher_id', 'in', $teacher_id)
        //     ->order('id', 'desc')
        //     ->select();
    
        $assignment_ids = array_column($assignments, 'id');

        // 获取学生已提交的作业（直接通过 homework 表查询）
        $submitted_assignments = $this->homework->dataMemberId('homework_assignment_relation har', 'h.id = har.homework_id',[
            'h.student_id' => $student_id,
            'har.assignment_id' => ['in', $assignment_ids]
        ], 'har.assignment_id');
    
        $teacherIds = array_unique(array_column($assignments, 'teacher_id'));

        // $teachers = Db::name('user')
        //     ->where('id', 'in', $teacherIds)
        //     ->column('username', 'id');
        $teachers = $this->user->dataMemberId([
            'id' => ['in', $teacherIds]
        ], 'username', 'id');
     
        $result = [];
        $today = date('Y-m-d');
        foreach ($assignments as $assignment) {
            $is_submitted = in_array($assignment['id'], $submitted_assignments) ? 1 : 0;
            $create_date = date('Y年m月d日 l', $assignment['create_time']); // 格式化为 "2025年07月01日 周三"
            $create_date_simple = date('Y-m-d', $assignment['create_time']);  // 简化日期，用于判断是否是今天
            $create_date = $this->convertWeekdayToChinese($create_date);
            if ($create_date_simple === $today) {
                $groupTitle = '今天';
            } else {
                $groupTitle = $create_date;  // 如果不是今天，则使用具体日期格式
            }
        
            // 获取作业的创建时间（格式化为日期）
            $create_date = date('Y-m-d', $assignment['create_time']); // 例如 "2025-07-01"
            

            // 如果需要获取 homework_id，可以这样查询
            $homework_id = $this->homework->dataValue('homework_assignment_relation har', 'h.id = har.homework_id', [
                'har.assignment_id' => $assignment['id'],
                'h.student_id' => $student_id
            ], 'h.id');

            // $homework_id = Db::name('homework h')
            //     ->join('homework_assignment_relation har', 'h.id = har.homework_id')
            //     ->where('h.student_id', $student_id)
            //     ->where('har.assignment_id', $assignment['id'])
            //     ->value('h.id');

            // 过滤作业：如果status为0，则只取未提交的作业
            if ($status === '1' && $is_submitted == 1) {
                continue; // 跳过已提交的作业
            }
    
            // 将作业分组
            if (!isset($result[$groupTitle])) {
                $result[$groupTitle] = [];
            }
    
            $result[$groupTitle][] = [
                'assignment_id' => $assignment['id'],
                'teacher_id' => $assignment['teacher_id'],
                'teacher_name' => $teachers[$assignment['teacher_id']] ?? null,
                'content' => $assignment['content'],
                'course_name' => $assignment['course_name'],
                'create_time' => $assignment['create_time'],
                'submit_status' => $is_submitted,
                'homework_id' => $homework_id
            ];
        }
    
        // 将分组数据格式化为最终结果
        $final_result = [];
        foreach ($result as $groupTitle => $items) {
            $final_result[] = [
                'groupTitle' => $groupTitle,
                'items' => $items
            ];
        }
    
        // 返回成功结果，作业按日期分组
        $this->success('查询成功', $final_result);
    }

    
    public function convertWeekdayToChinese($date){
        $weekdays = [
            'Sunday' => '周日', 'Monday' => '周一', 'Tuesday' => '周二', 
            'Wednesday' => '周三', 'Thursday' => '周四', 'Friday' => '周五', 'Saturday' => '周六'
        ];
        return str_replace(array_keys($weekdays), array_values($weekdays), $date);
    }


    /**
     * 查询作业详情表
     * @ApiTitle    (查询作业详情表)
     * @ApiMethod  (GET)
     * @ApiParams (name="assignment_id", type="int", required=true, description="布置作业ID")
     * @ApiParams (name="student_id", type="int", required=true, description="学生ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
          'code':'200',
          'msg':'查询成功',
          'time': "",
          'data': $row
        })
     */
    public function assignmentDetails()
    {
        $data = input('get.');
        $assignment_id = $data['assignment_id'];
        $student_id = $data['student_id'];

        // $assignment_id = $this->request->get('assignment_id');
        // $student_id = $this->request->get('student_id');
        
        // 参数验证
        if (empty($assignment_id)) {
            $this->error('作业ID不能为空');
        }
        if (empty($student_id)) {
            $this->error('学生ID不能为空'); 
        }
        if(!is_numeric($student_id) || !is_numeric($assignment_id)){
            $this->error('参数类型不正确');
        }

        $assignment = $this->model->dataInfo('user t', 'a.teacher_id = t.id', 'left' ,[
            'a.id' => $assignment_id,
        ], 'a.*, t.username as teacher_name');


        // 查询作业详情和老师信息
        // $assignment = $this->model->alias('a')
        //     ->join('user t', 'a.teacher_id = t.id', 'left')  
        //     ->where('a.id', $assignment_id)
        //     ->field('a.*, t.username as teacher_name')
        //     ->find();
        // return json($assignment);
        if (!$assignment) {
            $this->error('没有找到相关作业');
        }

        $reviews = $this->teacherreviews->dataInfo([
            'student_id' => $student_id,
            'homework_id' => $assignment_id,
        ], true, 'id desc');


        // $reviews = Db::name('teacher_reviews')
        //     ->where('student_id', $student_id)
        //     ->where('homework_id',$assignment_id)
        //     ->order('id', 'desc')
        //     ->find();


        // 查询作业关联信息

        $homework_relations = $this->homeworkAssignmentRelation->dataList([
            'assignment_id' => $assignment_id,
        ]);
        // $homework_relations = Db::name('homework_assignment_relation')
        //     ->where('assignment_id', $assignment_id)
        //     ->select();
        
        $homework_ids = array_column($homework_relations, 'homework_id');
        $homework = [];
        $submit_status = 0; // 默认未提交
        $correction = null;
        
        if (!empty($homework_ids)) {

            $homework = $this->homework->dataList([
                'id' => [ 'in', $homework_ids],
                'student_id' => $student_id,
            ]);
            // $homework = Db::name('homework')
            //     ->where('id', 'in', $homework_ids)
            //     ->where('student_id', $student_id)
            //     ->select();
                
            if ($homework) {
                $submit_status = 1; // 已提交
            }

            // 查询批改结果
            $correction = $this->homeworkCorrections->dataList([
                'student_id' => $student_id,
                'assignment_id' => $assignment_id,
            ]);

            // $correction = Db::name('homework_corrections')
            //     ->where('student_id', $student_id)
            //     ->where('assignment_id',$assignment_id)
            //     ->select();
        }
        
        //获取教师上传的图片
        $images = $this->homeworkAssignmentImageRelation->dataList([
            'assignment_id' => $assignment_id,
        ]);
        // $images = Db::name('homework_assignment_image_relation')
        //     ->where('assignment_id',$assignment_id)
        //     ->select();
        $assignment['images'] = $images;

        // 构建返回数据
        $result = [
            'assignment_details' => $assignment,
            'homework_details' => $homework ?: null,
            'submit_status' => $submit_status,
            'correction_result' => $correction?: null,
            'reviews' => $reviews?: null,
        ];

        $this->success('查询成功', $result);
    }

    /**
     * 老师查询作业详情
     * @ApiTitle    (老师查询作业详情)
     * @ApiMethod  (GET)
     * @ApiParams (name="assignment_id", type="int", required=true, description="布置作业ID")
     * @ApiParams (name="teacher_id", type="int", required=true, description="老师ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
          'code':'200',
          'msg':'查询成功',
          'time': "",
          'data': $row
        })
     */
    public function teacherAssignmentDetails()
    {
        $data = input('get.');
        $assignment_id = $data['assignment_id'];
        $teacher_id = $data['teacher_id'];
        // $assignment_id = $this->request->get('assignment_id');
        // $teacher_id = $this->request->get('teacher_id');
        
        // 参数验证
        if (empty($assignment_id)) {
            $this->error('作业ID不能为空');
        }
        if (empty($teacher_id)) {
            $this->error('老师ID不能为空');
        }

        // 1. 查询作业详情（带教师信息）
        $assignment = $this->model->dataInfo('user t', 'a.teacher_id = t.id', 'left' ,[
            'a.id' => $assignment_id,
        ], 'a.*, t.username as teacher_name');
        // $assignment = $this->model->alias('a')
        //     ->join('user t', 'a.teacher_id = t.id', 'left')  
        //     ->where('a.id', $assignment_id)
        //     ->field('a.*, t.username as teacher_name')
        //     ->find();
        
        if (empty($assignment)) {
            $this->error('没有找到相关作业');
        }

        // 2. 获取该教师管理的所有班级
        $classIds = $this->teacherClassesRelation->dataMemberId([
            'teacher_id' => $teacher_id,
        ], 'classes_id');
        // $classIds = Db::name('teacher_classes_relation')
        //     ->where('teacher_id', $teacher_id)
        //     ->column('classes_id');
        

        if (empty($classIds)) {
            $this->success('查询成功', [
                'assignment_details' => $assignment,
                'personnel' => []
            ]);
        }

        // 3. 获取这些班级的所有学生
        $studentIds = $this->studentClassesRelation->dataMemberId([
            'classes_id' => ['in', $classIds],
        ], 'student_id');

        // $studentIds = Db::name('student_classes_relation')
        //     ->where('classes_id', 'in', $classIds)
        //     ->column('student_id');
        
        if (empty($studentIds)) {
            $this->success('查询成功', [
                'assignment_details' => $assignment,
                'personnel' => []
            ]);
        }

        // 4. 获取学生基本信息
        $students = $this->user->dataList([
            'id' => ['in', $studentIds],
        ], 'id,username,avatar');

        // $students = Db::name('user')
        //     ->where('id', 'in', $studentIds)
        //     ->field('id,username,avatar')
        //     ->select();

        // 5. 获取该作业的所有提交记录
        $submissions = $this->homeworkAssignmentRelation->dataList([
            'har.assignment_id' => $assignment_id,
            'h.student_id' => ['in', $studentIds],
        ],'homework h', 'har.homework_id = h.id', 'left', 'h.id, h.student_id, h.status, h.original_image,h.create_time');

        // $submissions = Db::name('homework_assignment_relation')
        //     ->alias('har')
        //     ->join('homework h', 'har.homework_id = h.id')
        //     ->where('har.assignment_id', $assignment_id)
        //     ->where('h.student_id', 'in', $studentIds)
        //     ->field('h.id, h.student_id, h.status, h.original_image,h.create_time')
        //     ->select();

        // 按学生ID分组提交的作业
        $submissionsByStudent = [];
        foreach ($submissions as $submission) {
            $submissionsByStudent[$submission['student_id']][] = $submission;
        }

        $reviews = $this->teacherreviews->dataList([
            'student_id' => ['in', $studentIds],
            'homework_id' => $assignment_id,
        ]);
        // $reviews = Db::name('teacher_reviews')
        //     ->where('student_id', 'in', $studentIds)
        //     ->where('homework_id',$assignment_id)
        //     ->select();

        // 按学生ID分组点评
        $reviewsByStudent = [];
        foreach ($reviews as $review) {
            $reviewsByStudent[$review['student_id']][] = $review;
        }
        
        //获取教师上传的图片
        $images = $this->homeworkAssignmentImageRelation->dataList([
            'assignment_id' => $assignment_id,
        ]);
        // $images = Db::name('homework_assignment_image_relation')
        //     ->where('assignment_id',$assignment_id)
        //     ->select();
        $assignment['images'] = $images;

        $submitted = [];
        $notSubmitted = [];
        $submittedCount = 0;
        $notSubmittedCount = 0;
        $totalCount = count($students);

        // 7. 组装最终数据
        foreach ($students as &$student) {
            $studentId = $student['id'];
            if (isset($submissionsByStudent[$studentId])) {
                $submitted[] = [
                    'id' => $student['id'],
                    'username' => $student['username'],
                    'create_time' => $submissionsByStudent[$studentId][0]['create_time'],
                    'reviews' => isset($reviewsByStudent[$studentId]) ? $reviewsByStudent[$studentId] : []  // 将点评信息加到学生作业中
                ];
                $submittedCount++;
            } else {
                $notSubmitted[] = [
                    'id' => $student['id'],
                    'username' => $student['username'],
                ];
                $notSubmittedCount++;
            }
        }

        $submissionRate = $totalCount > 0 ? number_format(($submittedCount / $totalCount) * 100, 2) . '%' : '0%';

        // 返回最终数据
        $this->success('查询成功', [
            'assignment_details' => $assignment,
            'submitted_count' => $submittedCount,
            'not_submitted_count' => $notSubmittedCount,
            'totalCount' => $totalCount,
            'submission_rate' => $submissionRate,
            'submitted' => $submitted,
            'notSubmitted' => $notSubmitted,
        ]);
    }

    /**
     * 新增布置作业表
     * @ApiTitle    (新增布置作业表)
     * @ApiMethod  (POST)
     * @ApiParams (name="content", type="string", required=true, description="布置作业内容")
     * @ApiParams (name="teacher_id", type="int", required=true, description="教师ID")
     * @ApiParams (name="course_name", type="string", required=true, description="课程名称")
     * @ApiParams (name="teacher_img", type="array", required=true, description="图片地址")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="查询成功")
     * @ApiReturn   ({
        'code':'200',
        'msg':'查询成功',
        'time': "",
        'data': $row
        })
     */
    public function assignmentAdd(){
        $data = input('post.');
        if (empty($data['content']) || empty($data['teacher_id']) || empty($data['course_name'])) {
            return $this->error('参数错误');
        }
        $images = isset($data['teacher_img']) ? (array)$data['teacher_img'] : [];
        unset($data['teacher_img']);
        $row = $this->model->save($data);
        if (!empty($images)) {
            foreach ($images as $image){
                $imageData = [
                    'assignment_id' => $this->model->id,
                    'teacher_img' => $image
                ];
                $this->homeworkAssignmentImageRelation->dataAdd($imageData);
                // Db::name('homework_assignment_image_relation')->insert($imageData);
            }
        }

        if ($row) {
            return $this->success('新增成功');
        }
    }

}